package com.hxkcloud.nurse.fragments;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.activitys.MessageMainActivity;
import com.hxkcloud.nurse.adapter.RemindListAdapter;
import com.hxkcloud.nurse.alarm.Alarm;
import com.hxkcloud.nurse.alarm.Alarms;
import com.hxkcloud.nurse.beans.PatientRemindBean;
import com.hxkcloud.nurse.beans.RemindDateListBean;
import com.hxkcloud.nurse.beans.RemindTimeBean;
import com.hxkcloud.nurse.popup.CalendarPopWindow;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.StringUtil;
import com.hxkcloud.nurse.views.ListDividerItemDecoration;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableRecyclerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by william_sun on 2016-07-06.
 * Description:提醒模块
 */
public class RemindFragment extends BaseFragment implements View.OnClickListener, RemindListAdapter.ResultSelectedListener, PullToRefreshLayout.OnRefreshListener {

    private View view;

    private LinearLayout ll_title;
    private ImageView iv_calendar;
    private TextView tv_title;
    private ImageView iv_message;
    private ImageView iv_msgpoint;

    private LinearLayout ll_empty;
    private LinearLayout ll_info;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;

    private PullToRefreshLayout refreshLayout1;

    //    private List<String> stringInfoList;
    private RemindListAdapter adapter;

    private CalendarPopWindow calendarView;

    private List<RemindDateListBean.RemindDateBean> dates;//时间列表
    private List<PatientRemindBean> reminds;  //一天提醒列表
    private int dateType = 0;//日期早于今天0等于今天1今天后2

    private String curDay = "";

    private boolean isRefresh = false;

    private TextView emptyText;

    private RemindTimeBean remindTimeBean;//刷新也刷新提醒时间

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_PATIENTREMINDDATELIST_SUCCESS:
                dates = (List<RemindDateListBean.RemindDateBean>) msg.obj;
                if (dates != null && dates.size() > 0) {
                    showDates();
                } else {
//                    toastMsg(R.string.nodata);
                    refreshLayout1.setVisibility(View.VISIBLE);
//                    ll_info.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.GONE);
                    if (refreshLayout1 != null) {
                        if (isRefresh) {
                            refreshLayout1
                                    .refreshFinish(PullToRefreshLayout.SUCCEED);
                            isRefresh = false;
                        }
                    }
                }

                break;
            case MessageCode.NETWORKCODE_PATIENTREMINDDATELIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;
            case MessageCode.NETWORKCODE_PATIENTREMINDLIST_SUCCESS:
                reminds = (List<PatientRemindBean>) msg.obj;
                if (reminds != null && reminds.size() > 0) {
                    refreshLayout1.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);
                } else {
                    refreshLayout1.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

                String chooseDate = tv_title.getText().toString().trim();
                Calendar cal = Calendar.getInstance();
                String nowDate = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Long choose = Long.valueOf(0);
                Long now = Long.valueOf(0);
                try {
                    choose = sdf.parse(chooseDate).getTime();
                    now = sdf.parse(nowDate).getTime();
                } catch (ParseException e) {
                }
                if (choose < now) {
                    dateType = 0;
                } else if (choose > now) {
                    dateType = 2;
                } else {
                    dateType = 1;
                }
                if (adapter != null) {
                    adapter.setData(reminds, dateType);
                }
                if (refreshLayout != null) {
                    if (isRefresh) {
                        refreshLayout
                                .refreshFinish(PullToRefreshLayout.SUCCEED);
                        isRefresh = false;
                    }
                }

//                //成功后再获取提醒时间列表，不获取了，启动更新和极光推送去更新就够了
//                loading();
//                YiJiaHuNetWorkUtils.getRemindTimeList(handler);
                break;
            case MessageCode.NETWORKCODE_PATIENTREMINDLIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                refreshLayout
                        .refreshFinish(PullToRefreshLayout.SUCCEED);
                break;
            case MessageCode.NETWORKCODE_GETREMINDTIMELIST_SUCCESS:
                remindTimeBean = (RemindTimeBean) msg.obj;
                setRemindTime();
                break;
        }
    }

    public void showPoint(boolean show) {
        if (iv_msgpoint != null)
            if (show) {
                iv_msgpoint.setVisibility(View.VISIBLE);
            } else {
                iv_msgpoint.setVisibility(View.INVISIBLE);
            }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment_remind, container, false);

        initView();
        initListener();
//        initData();

        return view;

    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) view.findViewById(R.id.ll_title);
        iv_calendar = (ImageView) view.findViewById(R.id.iv_title_back);
        tv_title = (TextView) view.findViewById(R.id.tv_title_title);
        iv_message = (ImageView) view.findViewById(R.id.iv_title_func);
        iv_msgpoint = (ImageView) view.findViewById(R.id.iv_title_point);

        setTitlePadding(ll_title);
        iv_calendar.setVisibility(View.VISIBLE);
        iv_calendar.setImageResource(R.mipmap.remind_calendar);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        curDay = sdf.format(new Date());
        tv_title.setText(curDay);
        iv_message.setVisibility(View.VISIBLE);
        iv_message.setImageResource(R.mipmap.nav_message);
        iv_calendar.setOnClickListener(this);
        iv_message.setOnClickListener(this);

        ll_empty = (LinearLayout) view.findViewById(R.id.ll_department_empty);
//        ll_info = (LinearLayout) view.findViewById(R.id.ll_remind_info);

        emptyText = (TextView) view.findViewById(R.id.empty_text);
        emptyText.setText(mContext.getResources().getString(R.string.empty_remind_today));

        refreshLayout1 = (PullToRefreshLayout) view.findViewById(R.id.remind_fg_refreshlayout1);

        refreshLayout = (PullToRefreshLayout) view.findViewById(R.id.remind_fg_refreshlayout);
        recycleView = (PullableRecyclerView) view.findViewById(R.id.remind_fg_recyclerview);
        recycleView.setCanLoadMore(false);
        recycleView.setCanRefresh(true);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        ListDividerItemDecoration itemDecoration = new ListDividerItemDecoration(
                getActivity(), ListDividerItemDecoration.VERTICAL_LIST);
        recycleView.addItemDecoration(itemDecoration);

        reminds = new ArrayList<>();
        adapter = new RemindListAdapter(getActivity(), reminds, recycleView, this);
        recycleView.setAdapter(adapter);

        if (calendarView == null) {
            calendarView = new CalendarPopWindow(getActivity());
        }
        calendarView.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                boolean exist = false;
                if (dates != null && dates.size() > 0) {
                    for (RemindDateListBean.RemindDateBean d : dates) {
                        if (d.getDate().split(" ")[0].equals(calendar)) {
                            exist = true;
                        }
                    }
                }
                if (exist) {
                    tv_title.setText(calendar);
                    //get info
                    loading();
                    YiJiaHuNetWorkUtils.getRemindList(calendar, handler);
                } else {
//                    toastMsg(R.string.nodata);
                    tv_title.setText(calendar);
                    //get info
                    loading();
                    YiJiaHuNetWorkUtils.getRemindList(calendar, handler);
                }
//                if (dates != null && dates.size() > 0) {
//                    tv_title.setText(dates.get(dates.size() - 1).getDate().split(" ")[0]);
//                    loading();
//                    YiJiaHuNetWorkUtils.getRemindList(dates.get(dates.size() - 1).getDate().split(" ")[0], handler);
//                } else {
//                tv_title.setText(calendar);
//                loading();
//                YiJiaHuNetWorkUtils.getRemindList(dates.get(dates.size() - 1).getDate().split(" ")[0], handler);
            }
//            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(loginInfo.getDepartmentId())) {
            refreshLayout1.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        } else {
            initData();
            refreshLayout1.setVisibility(View.GONE);
//            ll_info.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.VISIBLE);
        }

        if (YjhApplication.msg_new) {
            iv_msgpoint.setVisibility(View.VISIBLE);
        } else {
            iv_msgpoint.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void initListener() {
        iv_calendar.setOnClickListener(this);
        iv_message.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout1.setOnRefreshListener(this);
    }

    @Override
    protected void initData() {
        if (dates == null || dates.size() == 0) {
            loading();
            YiJiaHuNetWorkUtils.getRemindDateList(handler);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                StringUtil.zhugeTrack(mContext, "日历按钮", "提醒模块日历按钮点击数");

                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
//                    calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                    BrightnessUtils.lightOff(getActivity());
                    calendarView.showBottom(ll_title);
                } else {
                    toastMsg(R.string.pleasefirstjoindepartment);
                }
                break;
            case R.id.iv_title_func:
                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                    Intent iM = new Intent(mContext, MessageMainActivity.class);
                    startActivity(iM);
                } else {
                    toastMsg(R.string.pleasefirstjoindepartment);
                }
                break;
        }
    }

    @Override
    public void onSelected(String type, String info) {

    }

    //日历上标注点
    private void showDates() {
        List<Calendar> calendars0 = new ArrayList<Calendar>();//普通提醒
        List<Calendar> calendars1 = new ArrayList<Calendar>();//二者都有
        List<Calendar> calendars2 = new ArrayList<Calendar>();//分娩日
        for (RemindDateListBean.RemindDateBean d : dates) {
            Calendar c = Calendar.getInstance();
            int year = Integer.valueOf(d.getDate().split(" ")[0].split("-")[0]);
            int month = Integer.valueOf(d.getDate().split(" ")[0].split("-")[1]) - 1;
            int day = Integer.valueOf(d.getDate().split(" ")[0].split("-")[2]);
            c.set(year, month, day);
            if (d.getType().equals("0")) {
                calendars0.add(c);
            } else if (d.getType().equals("2")) {
                calendars2.add(c);
            } else {
                calendars1.add(c);
            }
        }
        if (calendars1 != null && calendars1.size() > 0) {
            calendars0.addAll(calendars1);
            calendars2.addAll(calendars1);
        }
        calendarView.setPoints(calendars0, calendars2);
//        if (calendars0.size() > 0)
//            calendarView.setPoints(calendars0, 0);
//        if (calendars1.size() > 0)
//            calendarView.setPoints(calendars1, 1);
//        if (calendars2.size() > 0)
//            calendarView.setPoints(calendars2, 2);

//        tv_title.setText(dates.get(dates.size() - 1).getDate().split(" ")[0]);
        //get info
        loading();
//        YiJiaHuNetWorkUtils.getRemindList(dates.get(dates.size() - 1).getDate().split(" ")[0], handler);
        YiJiaHuNetWorkUtils.getRemindList(tv_title.getText().toString().trim(), handler);
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        if (loginInfo != null) {
            isRefresh = true;
//        refreshLayout
//                .refreshFinish(PullToRefreshLayout.SUCCEED);
//        loading();
            if (TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                refreshLayout1
                        .refreshFinish(PullToRefreshLayout.SUCCEED);
            } else {
                if (refreshLayout1.getVisibility() == View.VISIBLE) {
                    if (isRefresh) {
                        refreshLayout1
                                .refreshFinish(PullToRefreshLayout.SUCCEED);
                        isRefresh = false;
                    }
                }
                if (refreshLayout.getVisibility() == View.VISIBLE) {
                    if (isRefresh) {
                        refreshLayout
                                .refreshFinish(PullToRefreshLayout.SUCCEED);
                        isRefresh = false;
                    }
                }
                loading();
                YiJiaHuNetWorkUtils.getRemindDateList(handler);
            }
        }
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        refreshLayout1.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    private boolean isSetTime = false;

    //alarms refresh
    private void setRemindTime() {
        if (!isSetTime) {
            setRemindTimeTask task = new setRemindTimeTask();
            task.execute();
        }
    }

    private class setRemindTimeTask extends AsyncTask<Object, Object, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isSetTime = true;
//            loading();
        }

        @Override
        protected Boolean doInBackground(Object... params) {
            Alarms.clearAlarm(mContext);

            List<Long> times = new ArrayList<>();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            List<RemindTimeBean.rTime> rTimes = remindTimeBean.getRlist();
            List<RemindTimeBean.eTime> eTimes = remindTimeBean.getElist();
            for (RemindTimeBean.rTime rTime : rTimes) {
                for (String t : rTime.getTimeList()) {
                    String time = rTime.getRemindDate() + " " + t;
                    Long timeLong = (long) 0;
                    try {
                        timeLong = format.parse(time).getTime();
                    } catch (ParseException e) {
                    }
                    addTime(times, timeLong);
                }
            }
            Calendar c = Calendar.getInstance();
            Long now = c.getTime().getTime();
            for (RemindTimeBean.eTime eTime : eTimes) {
                for (String t : eTime.getTimeList()) {
                    String time = eTime.getEndDate() + " " + t;
                    Long timeLong = (long) 0;
                    try {
                        timeLong = format.parse(time).getTime();
                    } catch (ParseException e) {
                    }
                    for (long last = timeLong; last > now; last -= 24 * 60 * 60 * 1000) {
                        addTime(times, last);
                    }
                }
            }

            for (long time : times) {
                Date d = new Date(time);
                Calendar cTime = Calendar.getInstance();
                cTime.setTime(d);
                int hour = cTime.get(Calendar.HOUR_OF_DAY);
                int minute = cTime.get(Calendar.MINUTE);
                saveAlarm(time, time, hour, minute);
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
//            dismisssLoading();
            isSetTime = false;
            if (aBoolean) {
//do noting
            }
        }
    }

    private long saveAlarm(long date, long time, int mHour, int mMinutes) {
        Alarm alarm = new Alarm();
        alarm.enabled = true;
        alarm.hour = mHour;
        alarm.minutes = mMinutes;
        alarm.isDelay = false;
        alarm.date = date + "";
        alarm.time = time + "";

        long timee = 0;
        timee = Alarms.addAlarm(mContext, alarm);
        return timee;
    }

    private void addTime(List<Long> times, long time) {
        if (!times.contains(time)) {
            if (times.size() == 0) {
                times.add(0, time);
                return;
            } else if (times.size() == 1) {
                if (times.get(0) > time) {
                    times.add(0, time);
                    return;
                } else {
                    times.add(1, time);
                    return;
                }
            } else {
                if (time < times.get(0)) {
                    times.add(0, time);
                    return;
                } else if (time > times.get(times.size() - 1)) {
                    times.add(times.size(), time);
                    return;
                }
                for (int i = 0; i < times.size() - 1; i++) {
                    long time1 = times.get(i);
                    long time2 = times.get(i + 1);
                    if (time > time1 && time < time2) {
                        times.add(i + 1, time);
                        return;
                    }
                }
            }
        }
    }
}
